package com.example.sourcecodelearning.modules.file.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.example.framework.common.exception.ServiceException;
import com.example.module.system.enums.ErrorCodeConstants;
import com.example.sourcecodelearning.modules.file.dao.FileUploadDao;
import com.example.sourcecodelearning.modules.file.entity.FileUploadDO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@Service
public class FileUploadService {

    @Value("${file.dir}")
    private String fileDir;

    @Resource
    private FileUploadDao fileUploadDao;

    public Long upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String mainName = FileUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);
        String fileName = mainName + "_" + RandomUtil.randomString(8) + "." + extName;

        String absolutePath = fileDir + fileName;
        try {
            FileUtil.writeBytes(file.getBytes(), absolutePath);
        } catch (IOException e) {
            throw ServiceException.of(ErrorCodeConstants.FILE_UPLOAD_FAILED);
        }

        FileUploadDO fileUploadEntity = FileUploadDO.builder()
                .fileName(fileName)
                .filePath(absolutePath)
                .build();
        fileUploadDao.insert(fileUploadEntity);

        return fileUploadEntity.getId();
    }
}
